import { XMLNode } from '../xml-node';
import { BufferBuilder, RASTER_MODE } from '../buffer-builder';
import ndarray from 'ndarray';
import Image from '../image';
import pngjs from 'pngjs';
import jpegjs from 'jpeg-js';

const PNG = pngjs.PNG;

export default class ImageNode extends XMLNode {
  constructor(node: any) {
    super(node);
  }

  public open(bufferBuilder: BufferBuilder): BufferBuilder {
    let imageData: any;
    const base64 = this.content.replace(/&#x2F/g, '/').replace(/\/;/g, '/');
    if (base64.indexOf('image/jpeg') >= 0) {
      const result = base64.slice('data:image/jpeg;base64,'.length);
      const buffer = Buffer.from(result, 'base64');
      const data = jpegjs.decode(buffer, { useTArray: true });
      imageData = data;
    } else if (base64.indexOf('image/png') >= 0) {
      const result = base64.slice('data:image/png;base64,'.length);
      imageData = PNG.sync.read(Buffer.from(result, 'base64'));
    } else {
      throw new Error('cant convert base64 string');
    }
    const pixels = ndarray(
      new Uint8Array(imageData.data),
      [imageData.width | 0, imageData.height | 0, 4],
      [4, (4 * imageData.width) | 0, 1],
      0,
    );

    let mode;
    switch (this.attributes.mode) {
      case 'NORMAL':
        mode = RASTER_MODE.NORMAL;
        break;
      case 'DW':
        mode = RASTER_MODE.DOUBLE_WIDTH;
        break;
      case 'DH':
        mode = RASTER_MODE.DOUBLE_HEIGHT;
        break;
      case 'DWH':
        mode = RASTER_MODE.DOUBLE_WIDTH_HEIGHT;
        break;
      default:
        mode = RASTER_MODE.NORMAL;
    }

    bufferBuilder.printImage(new Image(pixels), mode);
    return bufferBuilder;
  }

  public close(bufferBuilder: BufferBuilder): BufferBuilder {
    return bufferBuilder;
  }
}
